package net.wenku8.reader.view.online

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import com.alibaba.fastjson2.JSON
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.wenku8.reader.api.BookApi
import net.wenku8.reader.entity.ApiResult
import net.wenku8.reader.enums.KeyOnlineReadHis
import net.wenku8.reader.model.book.Chapter
import net.wenku8.reader.service.FileService
import net.wenku8.reader.state.StateReadOnline
import net.wenku8.reader.util.formatTimeNum
import net.wenku8.reader.view.common.BaseViewModel
import java.util.Date

class OnlineReadViewModel : BaseViewModel() {

    var chapter by mutableStateOf(Chapter())
    var isText by mutableStateOf(true)
    val textList = mutableStateListOf<String>()
    var loaded by mutableStateOf(false)
    private val chapterList = ArrayList<Chapter>()
    private var chapterIndex = 0

    private val imageTag = "<!--image-->"
    private val imageUrlTag = "http"

    fun initData() {
        chapter = StateReadOnline.chapter.value
        loadBookData()
        initChapterIndex()
        loaded = true
    }

    fun changeChapter(left: Boolean){
        val nextChapter = getNextChapter(left)
        if (nextChapter != null){
            chapter = nextChapter
            textList.clear()
            loadBookData()
        }
    }

    private fun loadBookData(){
        viewModelScope.launch(Dispatchers.IO) {
            val apiResult = BookApi.getBookText(StateReadOnline.bookId.value, chapter.chapterId!!)
            if (ApiResult.isSuccess(apiResult)){
                val data = apiResult.data!!
                if (data.indexOf(imageTag) < 0){
                    textList.clear()
                    textList.addAll(data.split("\n").filter { it.trim().isNotEmpty() })
                    isText = true
                }else{
                    val list = ArrayList<String>()
                    list.addAll(data.split(imageTag))
                    list.removeIf {!it.startsWith(imageUrlTag) || it.isEmpty()}
                    textList.clear()
                    textList.addAll(list)
                    isText = false
                }
                saveReadHis()
            }else{
                showSnackbar(apiResult.message)
            }
        }
    }


    private fun initChapterIndex(){
        StateReadOnline.volumeList.value.forEach { volume ->
            if (volume.chapterList != null){
                chapterList.addAll(volume.chapterList)
            }
        }
        var index = -1
        for ((i, c) in chapterList.withIndex()){
            if (c.chapterId == chapter.chapterId){
                index = i
            }
        }
        chapterIndex = index
    }

    private fun getNextChapter(left : Boolean): Chapter?{
        val nextIndex = if (left) chapterIndex + 1 else chapterIndex - 1
        if (!left && nextIndex < 0 || left && nextIndex >= chapterList.size){
            return null
        }
        chapterIndex = nextIndex
        return chapterList[nextIndex]
    }

    private fun saveReadHis(){
        MMKV.defaultMMKV().encode(KeyOnlineReadHis + StateReadOnline.bookId, JSON.toJSONString(chapter))
    }

    fun saveImageByFile(fileName : String){
        viewModelScope.launch(Dispatchers.IO) {
            Log.i("saveImageByFile", fileName)
            val time = formatTimeNum(Date())
            val downloadFile = "wenku8_image_${time}.jpg"
            FileService.writeDownloadFile(fileName, downloadFile)
            showSnackbar("保存成功")
        }
    }

}